import { Injectable } from '@angular/core';
import { SHAPE_NAME_SEQ, Shape } from '../models/shape';

const PIECES = 7;

function _numToIdxSeq(num: number, pieces = PIECES) {
  let seq: number[] = Array(pieces);
  for (let i = 0, base = 1; i < pieces; base = ++i + 1) {
    seq[pieces - base] = num % base;
    num = num / base | 0;
  }
  return seq;
}

function _IdxSeqToPerm(seq: number[]) {
  let bag = Array(7).fill(null)
    , pieces = seq.length
    ;
  for (let i = 0; i < pieces; ++i) {
    let pieceIdx = seq[i];

    for (let j = 0, pos = -1; j < pieces; ++j) {
      if (bag[j] === null) {
        if (++pos === pieceIdx) {
          bag[j] = SHAPE_NAME_SEQ[i];
          break;
        }
      }
    }
  }
  return bag;
}

@Injectable()
export class PieceBag {

  permutation: Shape[] = [];

  getNext() {
    if (!this.permutation.length) {
      this.permutation = _IdxSeqToPerm(_numToIdxSeq(Math.random() * 5040 | 0));
    }
    return this.permutation.pop();
  }

}